package com.movisol.messengerprofileservice.asynctasks;

import java.util.List;

import android.os.AsyncTask;
import android.widget.Toast;

import com.movisol.messengerprofileservice.controllers.ProfileController;
import com.movisol.messengerprofileservice.data.Friend;
import com.movisol.messengerprofileservice.data.Friends;
import com.movisol.messengerprofileservice.exceptions.ProfileServiceWebFault;
import com.movisol.messengerprofileservice.helpers.MessengerProfileHelper;
import com.movisol.messengerprofileservice.interfaces.errorcodes.SaveUserProfileErrorCodes;
import com.movisol.tools.HelperUtils;

public class AsyncAddContact extends AsyncTask<Boolean, Void, String> {

	private ProfileController	pc				= ProfileController.getInstance();
	private Boolean				newInvitation	= null;

	@Override
	protected String doInBackground(Boolean... params) {
		newInvitation = params[0];
		String sku = HelperUtils.getConfigParam("SKU", pc.getContext());
		String version = HelperUtils.getApplicationVersion(pc.getContext());
		String languageId = HelperUtils.getDeviceCountry();
		String userId = pc.getUserProfile().getUserId();
		Friends friends = pc.fillFriendsObjectWithEmails(pc.getEmails(), null, null);
		return pc.updateUserFriends(sku, version, languageId, userId, friends);
	}

	/*
	 * (non-Javadoc)
	 * @see android.os.AsyncTask#onPostExecute(java.lang.Object)
	 */
	@Override
	protected void onPostExecute(String result) {
		super.onPostExecute(result);
		if (result != null)
		{
			List<Object> list = MessengerProfileHelper.parseXMLfriendsToObject(result);
			if (list.get(0) != null)
			{
				Friends answer = (Friends) list.get(0);
				if (newInvitation != null && newInvitation)
					for (Friend friend : answer.getFriendList())
						pc.getFriends().getFriendList().add(friend);
				HelperUtils.showToastMessage(pc.getContext(), "Invitation send", Toast.LENGTH_SHORT);
			}
			if (list.get(1) != null)
			{
				HelperUtils.LogE(getClass(), "cc.getMessagesCache() is NULL");
				HelperUtils.showToastMessage(pc.getContext(), SaveUserProfileErrorCodes
						.getErrorByCode(((ProfileServiceWebFault) list.get(1)).getIntegerErrorCode()),
						Toast.LENGTH_LONG);
			}
		} else
		{
			HelperUtils.LogE(getClass(), "cc.getMessagesCache() is NULL");
			HelperUtils.showToastMessage(pc.getContext(),
					SaveUserProfileErrorCodes.getErrorByCode(SaveUserProfileErrorCodes.INTERNAL_ERROR),
					Toast.LENGTH_LONG);
		}
	}
}
